/**
 * 
 */
package com.ntv.persistent.event;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import com.ntv.domain.IEvent;
import com.ntv.persistent.AbstractDao;
import com.ntv.persistent.PersistentException;

/**
 * @author Vedamoorthi Vairam
 * @since 03/02/2009
 *
 */
public class SqlEventDao extends AbstractDao implements IEventDao {
	
	private SimpleJdbcInsert insertEvent;
	
	interface CONST {
		interface QUERY {
			final String FIND_EVENTS_BY_DATE = " select 	event_id," +
					" event_start_time,	event_date, event_name,	event_category," +
					" created_by, created_date,	updated_by,	updated_date" +
					" from	events	where DATE_FORMAT(event_date,'%Y%m%d')  = DATE_FORMAT(now(),'%Y%m%d') limit 0, 50";
		}
	}
	
	public List<IEvent> getEvents() throws PersistentException 
	{
		return null;
	}
		
	public IEvent findEventByID(Long eventId) throws PersistentException 
	{
		return null;
	}
	
	public List<IEvent> findEventsByEventDate(Date eventDate) throws PersistentException 
	{
		
		
		return (List<IEvent>) getNamedParameterJdbcTemplate().query(
				CONST.QUERY.FIND_EVENTS_BY_DATE, new HashMap() , getRowMapper());
	}

	public IEvent createEvent(IEvent event)  throws PersistentException 
	{
		try
		{			
			insertEvent= new SimpleJdbcInsert(getJdbcTemplate())
				.withTableName(getTableName())			
				.usingGeneratedKeyColumns("event_id");
			
			Map<String, Object> parameters = new HashMap<String, Object>(10);
			parameters.put("event_start_time", event.getEventStartTime());
			parameters.put("event_date", event.getEventDate());
			parameters.put("event_name", event.getEventName());
			parameters.put("event_category", event.getEventCategory());		
			parameters.put("created_by", event.getCreatedBy() == null ? 0 : event.getCreatedBy());
			parameters.put("updated_by", event.getUpdatedBy() == null ? 0 : event.getUpdatedBy());
			parameters.put("created_date", new Date());
			parameters.put("updated_date", new Date());
			
			Number newId = insertEvent.executeAndReturnKey(parameters);
			event.setEventId(newId.longValue());
			
			return event;
		}
		catch (DataAccessException ex) 
		{
				throw new PersistentException(ex);
		}		
	}
}
